const $config = require("../config");
const $dispatchCenter = require("w-vue-chongqing/src/api/dispatchCenter");
const $dataIntegration = require("w-vue-chongqing/src/api/dataIntegration");
const $modelService = require("w-vue-chongqing/src/api/dataModel");
const $appService = require("w-vue-middle/api/appService");
const { scheduleCron } = require("w-vue-schedule/publicComponents");

export default {
  components: {
    scheduleCron
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {};
      }
    },
    modelInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    jobInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    type: {
      type: String,
      default: ""
    }
  },
  watch: {
    value(val) {
      this.formList = val;
      this.setData();
    },
    formList(val) {
      this.$emit("input", val);
    }
  },
  data() {
    return {
      activeKey: "1",
      initModelList: [],
      modelList: [],

      scheduleList: [],
      initJobGroupList: [],
      jobGroupList: [],
      jobHandlerList: [],
      clusterList: [],
      operModeList: [],
      routeList: [],
      misfireList: [],
      executorBlockList: [],
      formList: this.value,
      rules: {
        jobDesc: [{ required: true, message: $t("请输入任务名称"), trigger: "blur" }],
        scheduleType: [
          { required: true, message: $t("请选择调度类型"), trigger: "change" }
        ],
        scheduleCronConf: [
          { required: true, message: $t("请输入"), trigger: "blur" }
        ],
        jobGroup: [
          { required: true, message: $t("请选择执行器类型"), trigger: "change" }
        ],
        clusterId: [
          { required: true, message: $t("请选择集群"), trigger: "change" }
        ],
        executorHandler: [
          { required: true, message: $t("请选择执行器"), trigger: "change" }
        ],
        operatingMode: [
          { required: true, message: $t("请选择作业模式"), trigger: "change" }
        ],
        executorRouteStrategy: [
          { required: true, message: $t("请选择路由策略"), trigger: "change" }
        ],
        misfireStrategy: [
          { required: true, message: $t("请选择调度过期策略"), trigger: "change" }
        ],
        executorBlockStrategy: [
          { required: true, message: $t("请选择阻塞处理策略"), trigger: "change" }
        ],
        executorFailRetryCount: [
          { required: true, message: $t("请输入失败重试次数"), trigger: "blur" }
        ]
      },
      cronShow: false,
      scheduleLoading: false
    };
  },
  created() {
    this.initData();

    this.scheduleList = $config.scheduleList;
    this.operModeList = $config.operModeList;
    this.routeList = $config.routeList;
    this.executorBlockList = $config.executorBlockList;
    this.misfireList = $config.misfireList;
    this.getClusterList();
    if (this.type == "inteSchedule") {
      this.getHdwTables();
    }
  },
  methods: {
    initData() {
      this.formList = {
        ...$config.scheduleInfo,
        scheduleCronConf: $config.scheduleCronConf
      };
    },

    setData() {
      if (!this.formList.jobInfoId) {
        if ( this.modelInfo.tableCode) {
          !this.jobInfo.jobName && (this.jobInfo.jobName = this.modelInfo.tableCode);
          !this.formList.jobDesc && (this.formList.jobDesc = this.modelInfo.tableCode);
        }
      }

      if (!this.formList.scheduleType) {
        this.formList.scheduleType = "REALTIME";
      }

      let scheduleType = this.formList.scheduleType;
      let executorParam = this.formList.executorParam;
      let params = executorParam ? executorParam.split(",") : [];

      this.formList.newJobId = params[0] || undefined;
      this.formList.operatingMode =
        params[1] || (scheduleType == "REALTIME" ? "STREAMING" : "BATCH");
      this.formList.clusterId = params[2] || (this.clusterList.length > 0 ? this.clusterList[0].value : undefined);
      this.formList.otherTaskId = params.slice(3).join(",") || "";
      if (this.formList.jobInfoId) {
        this.setScheduleConf();
      } else {
        this.formList.scheduleCronConf = {
          second: "0",
          minute: "0/5",
          hour: "*",
          day: "*",
          month: "*",
          week: "?",
          year: ""
        };
        this.formList.sConf = "每月每日每时每5分";
      }
      this.getjobGroup();
    },
    /**
     * @Author: y_zp
     * @description: 获取调度模型数据
     */
    getHdwTables() {
      $modelService
        .getIndicatorTableData({
          pageNum: 1,
          pageSize: 100000,
          queryParams: {
            F_isDel_eq: 0
          }
        })
        .then(req => {
          this.initModelList = JSON.DeepCopy(req.data);
          this.searchModel();
        });
    },
    /**
     * @Author: y_zp
     * @description: 调度模型搜索
     */
    searchModel(val) {
      let templist = JSON.parse(JSON.stringify(this.initModelList));
      if (templist.length > 0) {
        if (val) {
          templist = templist.filter(item => {
            return (
              (item.tableName && item.tableName.indexOf(val) > -1) ||
              (item.tableCode && item.tableCode.indexOf(val) > -1)
            );
          });
        }
        templist = templist.slice(0, 15);
        if (this.modelInfo.tableCode) {
          let curItem = templist.find(item => {
            return item.tableCode == this.modelInfo.tableCode;
          });
          if (!curItem) {
            let itemVal = this.initModelList.find(item => {
              return item.tableCode == this.modelInfo.tableCode;
            });
            if (itemVal) {
              templist.unshift({ ...itemVal });
            }
          }
        }
      }
      this.modelList = templist.map(item => {
        return {
          ...item,
          label: item.tableName || item.tableCode,
          value: item.tableCode
        };
      });
    },
    /**
     * @Author: y_zp
     * @description: 切换模型
     */
    async changeModel() {
      let item = this.modelList.find(item => {
        return item.tableCode == this.modelInfo.tableCode;
      });
      this.$emit("change", item);
    },

    /**
     * @Author: y_zp
     * @description: 数据校验
     */
    toValidate(callback) {
      this.$refs.formList.validate(valid => {
        if (valid) {
          callback(true);
        } else {
          callback(false);
        }
      });
    },
    /**
     * @Author: y_zp
     * @description: 数据校验后获取数据
     */
    toValidateData() {
      let scheduleParams = {};
      let executorParam = "";
      let paramsList = [
        this.formList.newJobId || this.jobInfo.id,
        this.formList.operatingMode || "",
        this.formList.clusterId || "",
        this.formList.otherTaskId
      ];
      executorParam = paramsList.join(",");
      scheduleParams = {
        ...this.formList,
        executorParam,
        kafkaInuse: this.formList.kafkaInuse ? 1 : 0,
        sConf: undefined,
        newJobId: undefined,
        operatingMode: undefined,
        clusterId: undefined,
        otherTaskId: undefined
      };
      return scheduleParams;
    },
    /**
     * @Author: y_zp
     * @description: 切换调度类型
     */
    changeScheduleType() {
      if (this.formList.scheduleType == "CRON") {
        this.formList.operatingMode = "BATCH";
      } else if (this.formList.scheduleType == "REALTIME") {
        this.formList.operatingMode = "STREAMING";
      }
    },
    /**
     * @Author: y_zp
     * @description: 切换调度周期
     */
    changeScheduleConf(val) {
      this.formList.scheduleCronConf = val;
      this.setScheduleConf();
      this.$refs.scheduleCronForm.clearValidate();
    },
    setScheduleConf() {
      if (this.formList.scheduleType != "CRON") return;
      this.scheduleLoading = true;
      $dispatchCenter
        .translateCron(this.formList.scheduleCronConf)
        .then(req => {
          this.formList.sConf = req.data;
        })
        .finally(() => {
          this.scheduleLoading = false;
        });
    },
    /**
     * @Author: y_zp
     * @description: 切换执行器列表
     */
    changeJobGroup(val) {
      let item = this.jobGroupList.find(item => {
        return item.value == val;
      });
      this.formList.jobType = item.appType;
      // JobHandler过滤
      this.getJobHandler(item.appType, "changeHandler");
    },
    /**
     * @Author: y_zp
     * @description: 获取执行器列表
     */
    getjobGroup() {
      $dispatchCenter
        .getJobList({
          pageNum: 1,
          pageSize: 100,
          queryParams: {
            F_appType_eq: "transfer"
          }
        })
        .then(req => {
          this.initJobGroupList = JSON.DeepCopy(req.data);
          this.searchJobGroup();
        });
    },

    searchJobGroup(val) {
      let tempList = JSON.DeepCopy(this.initJobGroupList);
      if (val) {
        tempList = tempList.filter(item => {
          return (
            item.title &&
            item.title.toLocaleLowerCase().indexOf(val.toLocaleLowerCase()) > -1
          );
        });
      }

      tempList = tempList.slice(0, 15);

      if (this.formList.jobGroup) {
        let val = this.initJobGroupList.filter(item => {
          return item.jobGroupId == this.formList.jobGroup;
        });
        let idx = tempList.findIndex(item => {
          return item.jobGroupId == this.formList.jobGroup;
        });
        if (idx == -1) {
          tempList.unshift(val[0]);
        }
        this.getJobHandler(val[0].appType, "");
      } else {
        this.formList.jobGroup = tempList[0].jobGroupId;
        this.formList.jobType = tempList[0].appType;
        this.getJobHandler(tempList[0].appType, "");
      }
      this.jobGroupList = tempList.map(item => {
        return {
          label: item.title,
          value: item.jobGroupId,
          appType: item.appType
        };
      });
      this.$emit("update:modelInfo", this.modelInfo);
      this.$emit("update:jobInfo", this.jobInfo);
    },
    /**
       * @Author: y_zp
       * @description: 获取JobHandler
       */
    getJobHandler(remark, type) {
      $appService
        .getSysDictData({
          pageNum: 1,
          pageSize: 1000000,
          queryParams: {
            F_dictType_eq: "schedule_handler",
            F_isEnable_eq: 0,
            F_isDel_eq: 0,
            F_remark_eq: remark
          }
        })
        .then(req => {
          this.jobHandlerList = req.data.map(item => {
            return {
              label: item.dictLabel,
              value: item.dictValue
            };
          });
          if (!this.formList.executorHandler && this.jobHandlerList.length) {
            this.formList.executorHandler = this.jobHandlerList[0].value;
          }
        });
    },
    /**
     * @Author: y_zp
     * @description: 获取集群列表
     */
    getClusterList() {
      $dataIntegration
        .getClusterManager({
          pageNum: 1,
          pageSize: 10000,
          queryParams: {
            F_isDel_eq: 0
          }
        })
        .then(req => {
          this.clusterList = req.data.map(item => {
            return {
              value: item.clusterId,
              label: item.name
            };
          });

          if (!this.formList.clusterId && this.clusterList.length > 0) {
            this.formList.clusterId = this.clusterList[0].value;
          }
        });
    }
  }
};
